<?php

namespace App\Http\Middleware;

use App\Service\Admin\MenuService;
use Closure;
use Symfony\Component\HttpKernel\Exception\HttpException;

class CheckAdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $admin = $request->session()->get('admin');
        $can_action_array = ['index_','_','admin_update_pwd'];

        $menuService = new MenuService();
        $role_menu_action = $request->session()->get('role_menu_action');
        if($admin['role_id'] != 1){
            if(empty($role_menu_action)){
                $role_menu_action = $menuService->setRoleMenuAction($admin['role_id']);
            }
        }else{
            $role_menu_action = $menuService->setSuperRoleMenuAction();
        }
        if(empty($role_menu_action)){
            throw new HttpException(404, '未授权的角色，非法访问');
        }else{
            $url = $request->url();
            $url_array = explode('/',$url);
            if(count($url_array) == 4){
                $action = '_';
            }else if(count($url_array) == 5){
                $action = $url_array[4].'_';
            }else{
                $action = $url_array[4].'_'.$url_array[5];
            }
            if(!in_array($action, $can_action_array) && !in_array($action, $role_menu_action)){
                throw new HttpException(404, '无权限操作');
            }
        }
        return $next($request);
    }
}
